package com.market.sys.api.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.market.sys.common.Result;
import com.market.sys.entity.Notice;
import com.market.sys.service.INoticeService;
import com.market.sys.util.EmptyUtil;
import com.market.sys.util.PageForm;
import com.market.sys.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 * 公告表 前端控制器
 * </p>
 *
 * @author xd
 * @since 2024-03-30
 */
@RestController
@RequestMapping("/sys/admin/notice")
public class AdminNoticeController {

    @Autowired
    private INoticeService noticeService;

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable("id") Integer id){
        noticeService.removeById(id);
        return Result.success("删除成功");
    }

    @PostMapping("/save")
    public Result<?> save(@RequestBody Notice notice){
        if (Objects.isNull(notice)){
            return Result.error("提交信息不能为空！");
        }
        if (EmptyUtil.isNumberEmpty(notice.getId())){
            notice.setPublishTime(TimeUtil.timeYmdhm(new Date()));
        }
        boolean result = noticeService.saveOrUpdate(notice);
        if (result){
            return Result.success("操作成功");
        }
        return Result.error("操作失败");
    }

    @PostMapping("/list")
    public Result<Map<String ,Object>> search(@RequestBody PageForm form){
        LambdaQueryWrapper<Notice> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        Page<Notice> page = noticeService.page(new Page<>(form.getPageNo(), form.getPageSize()), lambdaQueryWrapper);

        Map<String,Object> data = new HashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());

        return Result.success(data);
    }

}
